import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

public class Server extends UnicastRemoteObject implements Server_itf{
	
	private HashMap<Integer, ServerObject> objs; //référence de chaque objets partagé
	private HashMap<String, Integer> index; 	 //Nom de l'objet
	private int genKey; 						 // générateur de référence unique
	
	protected Server() throws RemoteException {
		super();
		objs = new HashMap<Integer, ServerObject>();
		index = new HashMap<String, Integer>();
		genKey = 0;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//risque de réécriture sur un même id et saut d'id parce que non synchronized
	@Override
	public synchronized int create(Object o) throws RemoteException {
		
		int id = genKey;
		this.genKey++;
		objs.put(id, new ServerObject(id, o));
		return id;
	}

	@Override
	public Object lock_read(int id, Client_itf client) throws RemoteException {
		// TODO Auto-generated method stub
		if(!objs.containsKey(id)){
			System.out.println("Erreur objet introuvalble dans lock_read");
		}
		ServerObject temp = objs.get(id);
		return temp.lock_read(client);
	}

	@Override
	public Object lock_write(int id, Client_itf client) throws RemoteException {
		// TODO Auto-generated method stub
		if(!objs.containsKey(id)){
			System.out.println("Erreur objet introuvalble dans lock_write");
		}
		ServerObject temp = objs.get(id);
		return temp.lock_write(client);
	}

	@Override
	public int lookup(String name) throws RemoteException {
		// TODO Auto-generated method stub
		if(index.containsKey(name)){
			return index.get(name);
		}
		else
		{
			return -1;
		}
	}

	@Override
	public void register(String name, int id) throws RemoteException {
		// TODO Auto-generated method stub
		if(!index.containsKey(name)){
			index.put(name, id);
		}
		else
		{
			System.out.println("Unicité du nom sur l'objet " + name + " non respecté");
		}
	}
	
	public static void main(String[] argv){
		
		try {
			LocateRegistry.createRegistry(1099);
			
			//Création de l'objet serveur
			Server_itf serv = new Server();
			Naming.bind("rmi://localhost:1099/Serveur", serv);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AlreadyBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
